package com.zw.transition.controller;


import com.zw.transition.base.BaseController;
import com.zw.transition.common.JsonResult;
import com.zw.transition.entity.*;
import com.zw.transition.mapper.FlowMapper;
import com.zw.transition.services.AssemblyService;
import com.zw.transition.services.IndexService;
import com.zw.transition.util.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class IndexController extends BaseController {

    @Autowired
    private IndexService indexService;
    @Autowired
    private AssemblyService assemblyService;
    @Autowired
    private FlowMapper flowMapper;

    @Value("${user.upload.path}")
    private String uploadPath;

    /**
     * 跳转到首页
     */
    @GetMapping("/index")
    public String index(Model model) {
        return "/index";
    }

    /**
     * 跳转到历史申请
     */
    @GetMapping("/hisApply/{prodNo}/{drawNo}")
    public String hisApply(Model model,
                           @PathVariable("prodNo") String prodNo,
                           @PathVariable("drawNo") String drawNo
    ) {
        List<FlowTrans> list = indexService.findHisApplyList(prodNo, drawNo);
        if (list.size() == 1) {
            model.addAttribute("oldDataTrip", null);
            model.addAttribute("hisApply", list.get(0));
            return "/historicalApplyOper";
        } else if (list.size() > 1) {
            model.addAttribute("oldDataTrip", null);
            model.addAttribute("hisApply", list);
            return "/historicalApply";
        } else {
            List<FlowTrans> oldList = indexService.findHisApplyListOld(prodNo, drawNo);
            if (oldList.size() > 0) {
                model.addAttribute("oldDataTrip", "老版本数据无须转序！");
            } else {
                model.addAttribute("oldDataTrip", null);
            }
            return "/historicalApply";
        }
    }

    /**
     * 跳转到历史申请
     */
    @GetMapping("/gotoHisApplyOper/{id}")
    public String gotoHisApplyOper(Model model,
                                   @PathVariable("id") Integer id
    ) {
        model.addAttribute("hisApply", indexService.getHisApplyPrimaryKey(id));
        return "/historicalApplyOper";
    }

    /**
     * 跳转到历史接收列表页
     */
    @GetMapping("/hisRec/{prodNo}/{drawNo}")
    public String hisRec(Model model,
                         @PathVariable("prodNo") String prodNo,
                         @PathVariable("drawNo") String drawNo) {
        List<FlowTrans> list = indexService.findHisRecList(prodNo, drawNo);
        model.addAttribute("hisRec", list);
        if (list.size() > 1) {
            model.addAttribute("oldDataTrip", null);
            return "/historicalRec";
        } else if (list.size() == 1) {
            model.addAttribute("oldDataTrip", null);
            return "/historicalRecOper";
        } else {
            List<FlowTrans> oldlist = indexService.findHisRecListOld(prodNo, drawNo);
            if (oldlist.size() > 0) {
                model.addAttribute("oldDataTrip", "老版本数据无须转序！");
            } else {
                model.addAttribute("oldDataTrip", null);
            }
            return "/historicalRec";
        }
    }

    /**
     * 跳转到历史接收操作页面
     *
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/gotoHisRecOper/{id}")
    public String gotoHisRecOper(Model model,
                                 @PathVariable("id") Integer id) {
        model.addAttribute("hisRec", indexService.getHisRecByTransId(id));
        return "/historicalRecOper";
    }

    /**
     * 跳转到历史质检
     */
    @GetMapping("/hisCheck/{prodNo}/{drawNo}")
    public String hisCheck(Model model,
                           @PathVariable("prodNo") String prodNo,
                           @PathVariable("drawNo") String drawNo) {
        List<FlowTrans> list = indexService.findHisCheckList(prodNo, drawNo);
        model.addAttribute("hisCheck", list);
        if (list.size() == 1) {
            model.addAttribute("oldDataTrip", null);
            return "/historicalCheckOper";
        } else if (list.size() > 1) {
            model.addAttribute("oldDataTrip", null);
            return "/historicalCheck";
        } else {
            List<FlowTrans> oldList = indexService.findHisCheckListOld(prodNo, drawNo);
            if (oldList.size() > 0) {
                model.addAttribute("oldDataTrip", "老版本数据无须转序！");
            } else {
                model.addAttribute("oldDataTrip", null);
            }
            return "/historicalCheck";
        }
    }

    /**
     * 跳转到历史质检
     */
    @GetMapping("/gotoHisCheckOper/{id}")
    public String gotoHisCheckOper(Model model,
                                   @PathVariable("id") Integer id) {
        model.addAttribute("hisCheck", indexService.getHisCheckByTransId(id));
        return "/historicalCheckOper";
    }

    /**
     * 修改密码
     */
    @ResponseBody
    @PostMapping("/upp")
    public JsonResult uup(String pwd, HttpSession session) {
        User user = (User) session.getAttribute("user");
        user.setPwd(pwd);
        return jsonResult(indexService.updatePwd(user));
    }

    /**
     * 扫码
     */
    @GetMapping("/scan/{type}")
    public String scan(@PathVariable("type") Integer type, Model model) {
        model.addAttribute("type", type);
        return "scan";
    }

    /**
     * 申请，接收页面 此@PostMapping的值不要修改
     */
    @PostMapping("/result")
    public String scan(@RequestParam("type") Integer type,
                       @RequestParam("code") String code,
                       Model model) {
        try {
            model.addAttribute("url", "/scan/" + type);
            String content = "";
            FlowSheet sheet = indexService.findSheet(code);
            if (sheet == null) {
                return "codeIsNonExistent";
            }
            FlowTrans trips = new FlowTrans();
            trips.setProdNo(sheet.getProdNo());
            trips.setProName(sheet.getProName());
            trips.setProNum(sheet.getProNum());
            trips.setDrawNum(sheet.getDrawNum());
            trips.setDrawNo(sheet.getDrawNo());
            trips.setDrawName(sheet.getDrawName());
            trips.setType(sheet.getCategory());
            trips.setSpecial(sheet.getSpecial());
            trips.setPart(sheet.getPart());
            trips.setPartId(sheet.getPartId());
            trips.setProUnit(sheet.getProUnit());
            FlowRoute firstRoute = null;
            if (sheet == null) {
                model.addAttribute("content", "该工艺卡未接收！");
            } else {
                if (sheet.getDataVersion() != null) {
                    content = "老版本数据无须转序！";
                } else {
                    if(sheet.getCategory()!=3){
                        firstRoute = indexService.getFirstFlowRouteBySheetId(sheet.getId());
                        if (firstRoute != null && "原料".equals(firstRoute.getRoute()) && firstRoute.getOrderNo() == 10) {
                            if (firstRoute.getMayApplyNum() == 0 &&
                                    firstRoute.getApplyNum() == 0 &&
                                    firstRoute.getCheckNum() == 0) {
                                content = "该序为原料，待下料！";
                            }
                        } else if (firstRoute != null && firstRoute.getOrderNo() == 10 &&
                                firstRoute.getMayApplyNum() == 0 &&
                                firstRoute.getApplyNum() == 0 &&
                                firstRoute.getCheckNum() == 0) {
                            content = "该序为" + firstRoute.getRoute() + "，待下料！";
                        } else if (firstRoute == null) {
                            content = "该零件已全部转序！";
                        }
                    }
                }
            }
            model.addAttribute("sheet", indexService.findSheet(code));
            //如果是加工转序
            if (sheet.getCategory().intValue() == 1 || sheet.getCategory().intValue() == 3) {
                if (type == 1) {
                    if (!content.equals("") && sheet.getCategory().intValue() == 1) {
                        model.addAttribute("content", content);
                        model.addAttribute("tran", trips);
                        return "apply";
                    }
                    if (!content.equals("") && sheet.getCategory().intValue() == 3 && sheet == null) {
                        model.addAttribute("content", content);
                        trips.setTransMode(2);
                        model.addAttribute("tran", trips);
                        return "apply";
                    }
                    List<FlowTrans> list = new ArrayList<>();
                    if (sheet.getCategory().intValue() == 1) {
                        list = indexService.findApplyList(code);
                        if (content.equals("")) {
                            content = null;
                        }
                    }
                    if (sheet.getCategory().intValue() == 3) {
                        list = indexService.findApplyListByRepair(code);
                        content = null;
                    }
                    if (!"".equals(content)) {
                        model.addAttribute("content", content);
                    }
                    if (list.size() > 1) {
                        model.addAttribute("content", null);
                        model.addAttribute("list", list);
                        return "applyList";
                    } else if (list.size() == 1) {
                        model.addAttribute("content", null);
                        model.addAttribute("tran", list.get(0));
                        return "apply";
                    } else if (list.size() == 0) {
                        if (content == null || content.equals("")) {
                            content = "无路线或工序可以操作！";
                        }
                        model.addAttribute("content", content);
                        trips.setMayApplyNum(trips.getDrawNum());
                        model.addAttribute("tran", trips);
                        return "apply";
                    }
                } else if (type == 2) {
                    if (!content.equals("") && sheet.getCategory().intValue() == 1) {
                        model.addAttribute("tran", trips);
                        model.addAttribute("content", content);
                        return "check";
                    }
                    if (!content.equals("") && sheet.getCategory().intValue() == 3 && sheet == null) {
                        model.addAttribute("content", content);
                        model.addAttribute("tran", trips);
                        return "check";
                    }
                    List<FlowTrans> list = new ArrayList<>();
                    if (sheet.getCategory().intValue() == 1) {
                        list = indexService.findCheckList(code);
                        if (content.equals("")) {
                            content = null;
                        }
                    }
                    if (sheet.getCategory().intValue() == 3) {
                        list = indexService.findCheckListByRepair(code);
                        content = null;
                    }
                    if (list.size() > 0) {
                        model.addAttribute("list", list);
                    } else if (content != null && !"".equals(content)) {
                        model.addAttribute("tran", trips);
                        model.addAttribute("content", content);
                    }
                    if (list.size() > 1) {
                        return "checkList";
                    } else if (list.size() == 1) {
                        FlowTrans currentTrans = indexService.getTrans(list.get(0).getId());
                        FlowProcess process = indexService.getFlowProcessBySheetInfoAndRouteInfoAndProcessInfo(currentTrans);
                        if (process != null) {
                            currentTrans.setHandNo(process.getHandNo());
                        }
                        model.addAttribute("tran", currentTrans);
                        return "check";
                    } else if (list.size() == 0) {
                        if (content == null || content.equals("")) {
                            content = "无路线或工序可以操作！";
                        }
                        model.addAttribute("content", content);
                        model.addAttribute("tran", trips);
                        return "check";
                    }
                } else if (type == 3) {
                    if (!content.equals("") && sheet.getCategory().intValue() == 1) {
                        model.addAttribute("tran", trips);
                        model.addAttribute("content", content);
                        return "rec";
                    }
                    if (!content.equals("") && sheet.getCategory().intValue() == 3 && sheet == null) {
                        model.addAttribute("content", content);
                        model.addAttribute("tran", trips);
                        return "rec";
                    }
                    List<FlowTrans> list = new ArrayList<>();
                    if (sheet.getCategory().intValue() == 1) {
                        list = indexService.findRecList(code);
                        if (content.equals("")) {
                            content = null;
                        }
                    }
                    if (sheet.getCategory().intValue() == 3) {
                        list = indexService.findRecListListByRepair(code);
                        content = null;
                    }
                    if (list.size() > 0) {
                        model.addAttribute("list", list);
                    } else if (content != null && !"".equals(content)) {
                        model.addAttribute("tran", trips);
                        model.addAttribute("content", content);
                        return "rec";
                    }
                    if (list.size() > 1) {
                        return "recList";
                    } else if (list.size() == 1) {
                        FlowTrans currentTrans = indexService.getTrans(list.get(0).getId());
                        FlowProcess process = indexService.getFlowProcessBySheetInfoAndRouteInfoAndProcessInfo(currentTrans);
                        if (process != null) {
                            currentTrans.setHandNo(process.getHandNo());
                        }
                        model.addAttribute("tran", currentTrans);
                        return "rec";
                    } else if (list.size() == 0) {
                        if (content == null || content.equals("")) {
                            content = "无路线或工序可以操作！";
                        }
                        model.addAttribute("tran", trips);
                        model.addAttribute("content", content);
                        return "rec";
                    }
                }
            }
            //如果是装配转序
            else if (sheet.getCategory().intValue() == 2) {
                model.addAttribute("sheet", sheet);
                //申请质检
                if (type == 1) {
                    List<FlowTrans> list = indexService.findApplyListByAssembling(code);
                    model.addAttribute("list", list);
                    if (content != null && !content.equals("")) {
                        model.addAttribute("tran", trips);
                        model.addAttribute("content", content);
                        return "apply";
                    }
                    if (list.size() == 0) {
                        content = "无路线或工序可以操作！";
                        model.addAttribute("tran", trips);
                        model.addAttribute("content", content);
                        return "apply";
                    } else if (list.size() > 1) {
                        model.addAttribute("content", null);
                        model.addAttribute("list", list);
                        return "applyList";
                    } else if (list.size() == 1) {
                        model.addAttribute("content", null);
                        model.addAttribute("tran", list.get(0));
                        return "apply";
                    }
                }
                //质检
                else if (type == 2) {
                    if (!content.equals("")) {
                        model.addAttribute("tran", trips);
                        model.addAttribute("content", content);
                        return "check";
                    }
                    List<FlowTrans> list = indexService.findCheckListByAssembling(code);
                    if (list.size() > 0) {
                        model.addAttribute("list", list);
                    } else if (!"".equals(content)) {
                        content = "无路线或工序可以操作！";
                        model.addAttribute("tran", trips);
                        model.addAttribute("content", content);
                    }
                    if (list.size() > 1) {
                        return "checkList";
                    } else if (list.size() == 1) {
                        FlowTrans currentTrans = indexService.getTrans(list.get(0).getId());
                        model.addAttribute("tran", currentTrans);
                        return "check";
                    } else {
                        model.addAttribute("tran", trips);
                        content = "无路线或工序可以操作！";
                        model.addAttribute("content", content);
                        return "check";
                    }
                }
                //转序接收
                else if (type == 3) {

                    if (!content.equals("")) {
                        model.addAttribute("content", content);
                        model.addAttribute("tran", trips);
                        return "rec";
                    }
                    List<FlowTrans> list = indexService.findRecList(code);
                    if (list.size() > 0) {
                        //List<FlowRoute> completeList = indexService.findCompleteApplyList(code);
                        model.addAttribute("list", list);
                    } else if (!"".equals(content)) {
                        model.addAttribute("tran", trips);
                        model.addAttribute("content", content);
                    }
                    if (list.size() > 1) {
                        return "recList";
                    } else if (list.size() == 1) {
                        FlowTrans currentTrans = indexService.getTrans(list.get(0).getId());
                        FlowProcess process = indexService.getFlowProcessBySheetInfoAndRouteInfoAndProcessInfo(currentTrans);
                        if (process != null) {
                            currentTrans.setHandNo(process.getHandNo());
                        }
                        model.addAttribute("tran", currentTrans);
                        return "rec";
                    } else if (list.size() == 0) {
                        if (content == null || content.equals("")) {
                            content = "无路线或工序可以操作！";
                        }
                        model.addAttribute("content", content);
                        model.addAttribute("tran", trips);
                        return "rec";
                    }
                }
                return "error";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }


    /**
     * 申请质检
     */
    @ResponseBody
    @PostMapping("/apply")
    public JsonResult apply(FlowTrans trans) {
        return indexService.apply(trans);
    }

    /**
     * 质检驳回
     */
    @ResponseBody
    @PostMapping("/reject")
    public JsonResult reject(FlowCheck check) {
        return jsonResult(indexService.reject(check));
    }

    /**
     * 质检合格
     */
    @ResponseBody
    @PostMapping("/success")
    public JsonResult success(FlowCheck trans) {
        return jsonResult(indexService.success(trans));
    }

    /**
     * 接收
     */
    @ResponseBody
    @PostMapping("/rec")
    public JsonResult rec(FlowTrans trans) {
        return jsonResult(indexService.rec(trans));
    }

//    /**
//     * 历史申请
//     */
//    @ResponseBody
//    @GetMapping("/his/apply")
//    public JsonResult hisApply() {
//        List<FlowTrans> list = indexService.findHisApplyList();
//        return success().setData(list);
//    }

    /**
     * 删除
     */
    @ResponseBody
    @PostMapping("/delApply")
    public JsonResult delApply(Integer id) {
//        int rc = 0;
//        if (tranType.compareTo(1) == 0) {
//            /** 生产转序 **/
//            rc = indexService.delApply(id);
//        } else if (tranType.compareTo(2) == 0) {
//            /** 装配转序 **/
//            rc = assemblyService.delApply(id);
//        }
        return jsonResult(indexService.delApply(id));
    }

    /**
     * 重新申请
     */
    @ResponseBody
    @PostMapping("/repeatApply")
    public JsonResult repeatApply(Integer id, Integer tranType) {
        int rc = 0;
        if (tranType.compareTo(1) == 0) {
            /** 生产转序 **/
            rc = indexService.repeatApply(id);
        } else if (tranType.compareTo(2) == 0) {
            /** 装配转序 **/
            rc = assemblyService.repeatApply(id);
        }
        return jsonResult(rc);
    }

//    /**
//     * 历史接收
//     */
//    @ResponseBody
//    @GetMapping("/his/rec")
//    public JsonResult hisRec() {
//        List<FlowTrans> list = indexService.findHisRecList();
//        return success().setData(list);
//    }

    /**
     * 撤销接收
     */
    @ResponseBody
    @PostMapping("/cancel/rec")
    public JsonResult cancelRec(FlowTrans trans) throws Exception {
        return jsonResult(indexService.cancelRec(trans));
    }

    /**
     * 撤销申请
     */
    @ResponseBody
    @PostMapping("/cancel/apply")
    @Transactional(rollbackFor = Exception.class)
    public JsonResult cancelApply(FlowTrans trans) {
        User currentUser = (User) ServletUtils.getSession().getAttribute("user");
        //当前转序单
        trans = indexService.getFlowTransByPrimaryKey(trans.getId());
        if (trans.getRoute().equals("机加") && trans.getProcess().equals("划线") && trans.getType() == 1) {
            if (trans.getStatus() == 1) {
                return error("已撤销无需重复撤销！");
            }
            FlowRoute cur = flowMapper.findCurRoute(trans);
            FlowSheet sheet = flowMapper.getSheet(cur);
            boolean isPass = true;
            //厂级
            if (trans.getTransMode() == 1) {
                switch (trans.getStatus()) {
                    case 5: // 作废
                        sheet.setInvalid(sheet.getInvalid() - trans.getNum());
                        flowMapper.updateSheetInvalid(sheet);
                        break;
                    case 4: // 正常驳回
                        break;
                    case 3: // 倒数第二序
                        FlowRoute next = flowMapper.findNextRoute(cur);
                        if ("转储".equals(next.getRoute())) {
                            //获取对应的入库记录
                            AsseHalfStoreRecord record = flowMapper.getAsseHalfStoreRecordByPrimaryKey(trans.getRecordId());
                            //获取对应的库存
                            HalfStore halfStore = flowMapper.getHalfStore(record);
                            //如果
                            if (halfStore.getNum() < record.getDrawNum()) {
                                isPass = false;
                                break;
                            } else {
                                next.setRecNum(0);
                                next.setMayApplyNum(0);
                                next.setStatus(1);
                                flowMapper.updateRouteRecNum(next);
                                //生成对应的退库记录
                                AsseHalfStoreRecord returnStoreRecord = record;
                                returnStoreRecord.setRecordType(2);
                                returnStoreRecord.setReplaceId(record.getId());
                                returnStoreRecord.setStorageTime(new Date());
                                flowMapper.insertAsseHalfStoreRecord(returnStoreRecord);
                                halfStore.setNum(halfStore.getNum() - returnStoreRecord.getDrawNum());
                                flowMapper.updateHalfStoreNumByPrimary(halfStore);
                                trans.setRecordId(null);
                            }
                        } else if ("参焊".equals(next.getRoute())) {
                            next.setRecNum(0);
                            next.setMayApplyNum(0);
                            next.setStatus(1);
                            next.setRouteDate(null);
                            flowMapper.updateRoute(next);
                        }
                        break;
                    case 2: // 正常质检
                        break;
                }
                cur.setCheckNum(cur.getCheckNum() - trans.getNum());
                cur.setStatus(2);
                cur.setRouteDate(null);
                cur.setCanChange(1);
                flowMapper.updateRouteCheck(cur);
                //因撤销质检更新转序单表数据
                trans.setStatus(1);
                flowMapper.updateFlowTransByCancelCheck(trans);
                //删除质检数据
                //1.删除质检附件表数据
                FlowCheckAttachments deleteUpdateCheckAttachmentsObj = new FlowCheckAttachments();
                FlowCheck flowCheck = flowMapper.getFlowCheckByTransId(trans.getId());
                deleteUpdateCheckAttachmentsObj.setCheckId(flowCheck.getId());
                deleteUpdateCheckAttachmentsObj.setDeleteCode(currentUser.getAccount());
                deleteUpdateCheckAttachmentsObj.setDeleteName(currentUser.getName());
                if (currentUser.getBranchName() != null) {
                    deleteUpdateCheckAttachmentsObj.setDeleteDept(currentUser.getBranchName());
                }
                deleteUpdateCheckAttachmentsObj.setDeleteTime(new Date());
                deleteUpdateCheckAttachmentsObj.setIsDel(1);
                flowMapper.updateCheckAttachmentsByDelete(deleteUpdateCheckAttachmentsObj);
                //获取被删除的质检附件数据删除对应的附件
                List<FlowCheckAttachments> flowCheckAttachmentsList = flowMapper.findFlowCheckAttachmentsByRemove();
                //循环删除文件
                for (int i = 0; i < flowCheckAttachmentsList.size(); i++) {
                    String afterPath = "checkOrder/" + flowCheck.getId() + "/";
                    String allPath = uploadPath + afterPath;
                    File file = new File(allPath + flowCheckAttachmentsList.get(i).getAttFileName());
                    if (file.exists()) {
                        file.delete();
                    }
                }
                //2.删除质检表数据
                flowMapper.updateFlowCheckByByDelete(flowCheck);
            }
            //车间级
            else {
                //获取当前工序
                FlowProcess currentProcess = flowMapper.findCurProcess(trans);
                switch (trans.getStatus()) {
                    case 5: // 作废
                        sheet.setInvalid(sheet.getInvalid() - trans.getNum());
                        flowMapper.updateSheetInvalid(sheet);
                        break;
                    case 4: // 正常驳回
                        break;
                    case 3: // 倒数第二序
                        FlowRoute next = flowMapper.findNextRoute(cur);
                        if ("转储".equals(next.getRoute())) {
                            //获取对应的入库记录
                            AsseHalfStoreRecord record = flowMapper.getAsseHalfStoreRecordByPrimaryKey(trans.getRecordId());
                            //获取对应的库存
                            HalfStore halfStore = flowMapper.getHalfStore(record);
                            //如果
                            if (halfStore.getNum() < record.getDrawNum()) {
                                isPass = false;
                                break;
                            } else {
                                next.setRecNum(0);
                                next.setMayApplyNum(0);
                                next.setStatus(1);
                                flowMapper.updateRouteRecNum(next);
                                //生成对应的退库记录
                                AsseHalfStoreRecord returnStoreRecord = record;
                                returnStoreRecord.setRecordType(2);
                                returnStoreRecord.setReplaceId(record.getId());
                                returnStoreRecord.setStorageTime(new Date());
                                flowMapper.insertAsseHalfStoreRecord(returnStoreRecord);
                                halfStore.setNum(halfStore.getNum() - returnStoreRecord.getDrawNum());
                                flowMapper.updateHalfStoreNumByPrimary(halfStore);
                                trans.setRecordId(null);
                            }
                        } else if ("参焊".equals(next.getRoute())) {
                            next.setRecNum(0);
                            next.setMayApplyNum(0);
                            next.setStatus(1);
                            next.setRouteDate(null);
                            flowMapper.updateRoute(next);
                        }
                        break;
                    case 2: // 正常质检
                        break;
                }
                currentProcess.setCheckNum(currentProcess.getCheckNum() - trans.getNum());
                currentProcess.setStatus(2);
                currentProcess.setProcessDate(null);
                flowMapper.updateProcessCheck(currentProcess);
                //获取当前工序的路线最后一道工序
                FlowProcess currentRoteLastProceee = flowMapper.getCurrentRouteLastProcess(currentProcess);
                //如果当前工序是同路线的租后一道工序
                if (currentRoteLastProceee.getOrderNum() == currentProcess.getOrderNum()) {
                    //获取当前路线    往回反写数量
                    FlowRoute currentProcessRoute = flowMapper.getFlowRouteByPrimaryKey(currentRoteLastProceee.getRouteId());
                    currentProcessRoute.setCheckNum(currentProcessRoute.getCheckNum() - trans.getNum());
                    currentProcessRoute.setStatus(2);
                    currentProcessRoute.setRouteDate(null);
                    currentProcessRoute.setCanChange(1);
                    flowMapper.updateRouteCheck(currentProcessRoute);
                }
                //因撤销质检更新转序单表数据
                trans.setStatus(1);
                flowMapper.updateFlowTransByCancelCheck(trans);
                //删除质检数据
                //1.删除质检附件表数据
                FlowCheckAttachments deleteUpdateCheckAttachmentsObj = new FlowCheckAttachments();
                FlowCheck flowCheck = flowMapper.getFlowCheckByTransId(trans.getId());
                deleteUpdateCheckAttachmentsObj.setCheckId(flowCheck.getId());
                deleteUpdateCheckAttachmentsObj.setDeleteCode(currentUser.getAccount());
                deleteUpdateCheckAttachmentsObj.setDeleteName(currentUser.getName());
                if (currentUser.getBranchName() != null) {
                    deleteUpdateCheckAttachmentsObj.setDeleteDept(currentUser.getBranchName());
                }
                deleteUpdateCheckAttachmentsObj.setDeleteTime(new Date());
                deleteUpdateCheckAttachmentsObj.setIsDel(1);
                flowMapper.updateCheckAttachmentsByDelete(deleteUpdateCheckAttachmentsObj);
                //获取被删除的质检附件数据删除对应的附件
                List<FlowCheckAttachments> flowCheckAttachmentsList = flowMapper.findFlowCheckAttachmentsByRemove();
                //循环删除文件
                for (int i = 0; i < flowCheckAttachmentsList.size(); i++) {
                    String afterPath = "checkOrder/" + flowCheck.getId() + "/";
                    String allPath = uploadPath + afterPath;
                    File file = new File(allPath + flowCheckAttachmentsList.get(i).getAttFileName());
                    if (file.exists()) {
                        file.delete();
                    }
                }
                //2.删除质检表数据
                flowMapper.updateFlowCheckByByDelete(flowCheck);
            }
            //如果是生产转序
            if (trans.getType() == 1) {
                //当前路线
                FlowRoute currentFlowRoute = indexService.getFlowRouteByPrimaryKey(trans.getRouteId());
                //如果是厂级
                if (trans.getTransMode() == 1) {
                    //判断下序申请数量是否为0，如果是0就可撤销
                    if ((currentFlowRoute.getCheckNum() == null || currentFlowRoute.getCheckNum() == 0) || currentFlowRoute.getApplyNum() - currentFlowRoute.getCheckNum() >= trans.getNum()) {
                        return jsonResult(indexService.cancelApply(trans));
                    }
                    //如果不为0，则不可撤销
                    else {
                        return error("此转序已质检无法撤销申请！");
                    }
                }
                //如果是车间级
                else if (trans.getTransMode() == 2) {
                    FlowProcess process = indexService.getFlowProcessByPrimaryKey(trans.getProcessId());
                    //如果要当前路线下首序工序
                    if (process.getOrderNum() == 1) {
                        //当前路线
                        FlowRoute route = indexService.getFlowRouteByPrimaryKey(trans.getRouteId());
                        route.setApplyNum(trans.getNum());
                        indexService.updateCancelRouteApply(route);
                    }
                    //判断下序申请数量是否为0，如果是0就可撤销
                    if ((process.getCheckNum() == null || process.getCheckNum() == 0) || process.getApplyNum() - process.getCheckNum() >= trans.getNum()) {
                        return jsonResult(indexService.cancelApplyForProcess(trans));
                    }
                    //如果不为0，则不可撤销
                    else {
                        return error("此转序已质检无法撤销申请！");
                    }
                }
            }
        } else {
            //如果是生产转序
            if (trans.getType() == 1) {
                //当前路线
                FlowRoute currentFlowRoute = indexService.getFlowRouteByPrimaryKey(trans.getRouteId());
                //如果是厂级
                if (trans.getTransMode() == 1) {
                    //判断下序申请数量是否为0，如果是0就可撤销
                    if ((currentFlowRoute.getCheckNum() == null || currentFlowRoute.getCheckNum() == 0) || currentFlowRoute.getApplyNum() - currentFlowRoute.getCheckNum() >= trans.getNum()) {
                        return jsonResult(indexService.cancelApply(trans));
                    }
                    //如果不为0，则不可撤销
                    else {
                        return error("此转序已质检无法撤销申请！");
                    }
                }
                //如果是车间级
                else if (trans.getTransMode() == 2) {
                    FlowProcess process = indexService.getFlowProcessByPrimaryKey(trans.getProcessId());
                    //如果要当前路线下首序工序
                    if (process.getOrderNum() == 1) {
                        //当前路线
                        FlowRoute route = indexService.getFlowRouteByPrimaryKey(trans.getRouteId());
                        route.setApplyNum(trans.getNum());
                        indexService.updateCancelRouteApply(route);
                    }
                    //判断下序申请数量是否为0，如果是0就可撤销
                    if ((process.getCheckNum() == null || process.getCheckNum() == 0) || process.getApplyNum() - process.getCheckNum() >= trans.getNum()) {
                        return jsonResult(indexService.cancelApplyForProcess(trans));
                    }
                    //如果不为0，则不可撤销
                    else {
                        return error("此转序已质检无法撤销申请！");
                    }
                }

            }
            //如果是派工转序
            else if (trans.getType() == 2) {
                // 如果已经被质检
                FlowCheck flowCheck = indexService.getFlowCheckByTransId(trans.getId());
                if (flowCheck != null && trans.getStatus() == 2) {
                    return error("此转序已质检无法撤销申请！");
                }
                FlowRoute flowRoute = indexService.getFlowRouteByPrimaryKey(trans.getRouteId());
                flowRoute.setApplyNum(trans.getNum());
                int res = indexService.updateRouteApplyToCancelApply(flowRoute);
                trans.setIsDel(1);
                //删除转序单
                res += indexService.updateFlowTransIsdel(trans);
                // 如果没申请质检，转序状态设置成未开始
                res += indexService.updateRouteStatusNotStarted(flowRoute.getId());
                return success("撤销成功！");
            }
            //如果是返修转序
            else if (trans.getType() == 3) {
                trans.setIsDel(1);
                indexService.updateFlowTransIsdel(trans);
                return success("撤销成功！");
            } else {
                return error("撤销发生错误，请重新撤销！");
            }
        }
        return error("撤销发生错误，请重新撤销！");
    }

    /**
     * 撤销质检
     */
    @ResponseBody
    @PostMapping("/cancel/check")
    public JsonResult cancelCheck(FlowTrans trans) {
        return jsonResult(indexService.cancelCheck(trans));
    }

//    /** 围猫 */
//    @GetMapping("/cat")
//    public String catchcat() {
//        return "catch";
//    }
//
//    @GetMapping("/test")
//    public String testPage() {
//        return "apply";
//    }

    /**
     * 返回首页
     */
    @GetMapping("/goIndex")
    public String goIndex() {
        return "index";
    }

    /**
     * 首次质检后编辑质检单
     *
     * @param result
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/editCheckInfo/{result}/{id}")
    public String editCheckInfoResult(@PathVariable("result") String result,
                                      @PathVariable("id") Integer id,
                                      Model model) {
        model.addAttribute("result", result);
        model.addAttribute("tran", indexService.getTrans(id));
        FlowCheck check = indexService.getFlowCheckByTransId(id);
        model.addAttribute("check", check);
        return "uploadCheckOrder";
    }

    /**
     * 历史质检编辑质检单
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/editCheckInfo/{id}")
    public String editCheckInfo(@PathVariable("id") Integer id,
                                Model model) {
        model.addAttribute("tran", indexService.getTrans(id));
        FlowCheck check = indexService.getFlowCheckByTransId(id);
        model.addAttribute("check", check);
        return "uploadCheckOrder";
    }


    /**
     * 新增/保存编辑的质检单
     *
     * @param files
     * @param request
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @ResponseBody
    @PostMapping("/saveCheckOrders")
    public JsonResult saveCheckOrders(@RequestParam(value = "files") MultipartFile[] files,
                                      @RequestParam(value = "removeFiles") String[] removeFiles,
                                      HttpServletRequest request) throws ServletException, IOException {
        return indexService.saveCheckOrders(files, removeFiles, request);
    }

    /**
     * 跳转到质检明细页面
     *
     * @param id
     * @return
     */
    @GetMapping("/gotoCheckDetailPage/{id}")
    public String gotoCheckDetailPage(@PathVariable("id") Integer id,
                                      Model model) {
        FlowTrans currentTrans = indexService.getTrans(id);
        FlowProcess process = indexService.getFlowProcessBySheetInfoAndRouteInfoAndProcessInfo(currentTrans);
        if (process != null) {
            currentTrans.setHandNo(process.getHandNo());
        }
        model.addAttribute("tran", currentTrans);
        return "check";
    }

    /**
     * 跳转到接收明细页面
     *
     * @param id
     * @return
     */
    @GetMapping("/gotoRecDetailPage/{id}")
    public String gotoRecDetailPage(@PathVariable("id") Integer id,
                                    Model model) {
        FlowTrans currentTrans = indexService.getTrans(id);
        FlowProcess process = indexService.getFlowProcessBySheetInfoAndRouteInfoAndProcessInfo(currentTrans);
        if (process != null) {
            currentTrans.setHandNo(process.getHandNo());
        }
        model.addAttribute("tran", currentTrans);
        return "rec";
    }

    /**
     * 跳转到申请质检明细页面
     *
     * @return
     */
    @GetMapping("/gotoApplyDetailPage/{sheetId}/{routeId}/{processId}")
    public String gotoApplyDetailPage(@PathVariable("sheetId") Integer sheetId,
                                      @PathVariable("routeId") Integer routeId,
                                      @PathVariable("processId") Integer processId,
                                      Model model) {
        FlowSheet sheet = indexService.getFlowSheetByPrimaryKey(sheetId);
        if (sheet == null) {
            model.addAttribute("content", "该工艺卡已删除无法转序！");
        } else {
            FlowTrans currentTrans;
            if (sheet.getCategory().intValue() != 3) {
                currentTrans = indexService.getFlowTransBySheetIdAndRouteIdAndProcessId(sheetId, routeId, processId);
            } else {
                currentTrans = indexService.getFlowTransBySheetIdForRepair(sheetId);
            }
            model.addAttribute("tran", currentTrans);
        }
        return "apply";
    }

    /**
     * 获取质检附件列表
     *
     * @param checkId
     * @return
     */
    @ResponseBody
    @PostMapping("/loadCheckAttachments")
    public JsonResult loadCheckAttachments(Integer checkId) {
        List<FlowCheckAttachments> attachmentsList = indexService.findFlowCheckAttachmentsByCheckId(checkId);
        return jsonResult(attachmentsList);
    }
}
